package text

import (
	"beesoft.ink/application/media/app/helper/org/beesoft/chat"
	"fmt"
	"github.com/kataras/iris/v12"
	"regexp"
)

var Text text

type text struct{}

func (r *text) Sse(ctx iris.Context) {
	ctx.Header("Content-Type", "text/event-stream")
	ctx.Header("Cache-Control", "no-cache")
	ctx.Header("Connection", "keep-alive")

	err := chat.NewChat().
		Stream(func(content string) error {
			_, err := ctx.WriteString(content)
			if err != nil {
				return err
			}

			ctx.ResponseWriter().Flush()

			return nil
		})
	if err != nil {
		fmt.Println("chat error", err)
		return
	}

	for {
		select {
		case <-ctx.Done():
			fmt.Println("Client disconnected: Sse")
			return
		default:
		}
	}
}
func (r *text) Stream(ctx iris.Context) {
	ctx.Header("Content-Type", "text/plain")
	ctx.Header("Cache-Control", "no-cache")
	ctx.Header("Connection", "keep-alive")

	err := chat.NewChat().
		Stream(func(content string) error {
			pattern := `data: (.*?)\n`
			re := regexp.MustCompile(pattern)
			matches := re.FindStringSubmatch(content)

			if len(matches) > 1 {
				for _, match := range matches[1:] {
					_, err := ctx.WriteString(match + "\n")
					if err != nil {
						fmt.Println("Error writing to response:", err)
						return err
					}

					ctx.ResponseWriter().Flush()
				}
			} else {
				fmt.Println("Steam No match found: ", content)
			}

			return nil
		})
	if err != nil {
		fmt.Println("chat error", err)
		return
	}

	for {
		select {
		case <-ctx.Done():
			fmt.Println("Client disconnected: Stream")
			return
		default:
		}
	}
}
